package blog

import (
	"fmt"
	kcommon "longblog/framework/tools/common"
	kinit "longblog/work/base/initialize"
	kroute "longblog/work/base/route"
	kbase "longblog/work/control/base"
	"net/http"
	"os"
	"path"
	"strings"

	"github.com/gin-gonic/gin"
)

type Upload struct {
}

func NewUpload() *Upload {
	return &Upload{}
}

func (u *Upload) Load() (route []kroute.RouteWrapStruct) {
	route = make([]kroute.RouteWrapStruct, 0, 1)
	route = append(route, kbase.Wrap("POST", "/blog/upload/:path", u.EditorUploadHandle, kbase.MIDDLE_TYPE_NO_CHECK_LOGIN))
	return
}

func (u *Upload) EditorUploadHandle(c *gin.Context) {

	pathx := kbase.GetParam(c, "path")
	file, _ := c.FormFile("editormd-image-file")

	fileExt := strings.ToLower(path.Ext(file.Filename))
	if !(fileExt == ".jpg" || fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".bmp") {
		c.JSON(http.StatusOK, gin.H{
			"error":   1,
			"message": "请上传jpg|jpeg|png|bmp 格式的图片",
			"url":     "",
		})
		return
	}
	fileName := kinit.SnowflakeNode.Generate().String() + kcommon.GetRandomString(4, 0) + fileExt
	savePath := fmt.Sprintf("view/upload/%s/%s", pathx, fileName)
	urlPath := fmt.Sprintf("/upload/%s/%s", pathx, fileName)

	os.MkdirAll(fmt.Sprintf("view/upload/%s", pathx), 755)
	err := c.SaveUploadedFile(file, savePath)
	if err != nil {
		kinit.LogError.Println(err)

		c.JSON(http.StatusOK, gin.H{
			"success": 0,
			"message": "上传失败",
			"url":     "",
		})
		return
	}
	// /upload/kindedtior/
	c.JSON(http.StatusOK, gin.H{
		"success": 1,
		"message": "上传成功",
		"url":     urlPath, //
	})
}
